package com.powernode.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysUser;
import com.powernode.domain.SysUserRole;
import com.powernode.mapper.SysUserMapper;
import com.powernode.mapper.SysUserRoleMapper;
import com.powernode.service.SysUserRoleService;
import com.powernode.service.SysUserService;
import com.powernode.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 内容:
 * 作者: cy
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 分页查询管理员列表
     * 分页查询一般不需要添加缓存
     *
     * @param page
     * @param sysUser
     * @return
     */
    @Override
    public Page<SysUser> selectSysUserPage(Page<SysUser> page, SysUser sysUser) {
        // 需要查询当前店铺的用户列表
        Long shopId = AuthUtil.getUserIdOrShopId(false);
        return sysUserMapper.selectPage(page, new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getShopId, shopId)
                .like(StringUtils.hasText(sysUser.getUsername()), SysUser::getUsername, sysUser.getUsername())
                .orderByDesc(SysUser::getCreateTime)
        );
    }


    /**
     * 新增管理员
     *
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(SysUser sysUser) {
        // 需要拿到当前用户
        Long userId = AuthUtil.getUserIdOrShopId(true);
        // 需要拿到当前店铺
        Long shopId = AuthUtil.getUserIdOrShopId(false);
        log.info("新增管理员{},用户id为{}，店铺id为{}", JSON.toJSONString(sysUser), userId, shopId);
        sysUser.setCreateUserId(userId);
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(shopId);
        // 密文
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePwd = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(encodePwd);
        // 插入数据库
        int i = sysUserMapper.insert(sysUser);
        if (i > 0) {
            // 写 用户角色中间表
            List<Long> roleIdList = sysUser.getRoleIdList();
            if (!CollectionUtils.isEmpty(roleIdList)) {
                ArrayList<SysUserRole> sysUserRoles = new ArrayList<>(roleIdList.size());
                // 循环角色id的集合
                roleIdList.forEach(rid -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(rid);
                    sysUserRole.setUserId(sysUser.getUserId());
                    // 不要在循环中操作数据库  <foreach  大部分场景 不要这样做
//                    sysUserRoleMapper.insert(sysUserRole);
                    sysUserRoles.add(sysUserRole);
                });
                sysUserRoleService.saveBatch(sysUserRoles);
            }
        }
        return i > 0;
    }
}
